package mi.payment.transaction;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import lainey.ui.utils.LogUtil;
import lainey.ui.widget.TitleView;
import mi.payment.R;
import mi.payment.constants.Configs;
import mi.payment.constants.Params;
import mi.payment.ui.print.helper.PrintController;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.SalesSlipPrintSettingsOperation;
import mi.payment.ui.base.ParentActivity;
import mi.payment.ui.print.BasePrintCallback;
import mi.payment.utils.UIUtils;
import mi.payment.utils.print.DataPrinterKernel;
import woyou.aidlservice.jiuiv5.ICallback;

public class WaitPrintActivity extends ParentActivity {

    private ImageView mIvState;
    private TextView mTvState;
    private TextView mTvHint;

    private int mTitleResId;
    private int mIconResId;
    private String mResultStr;
    private PayDetail mPayDetail;

    private int mCountDownTime = 0;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            mCountDownTime++;
            try {
                int state = DataPrinterKernel.INSTANCE().updatePrinterState();
                if (state == 1) {
                    mHandler.removeMessages(0);
                    resetPrint();
                    return;
                } else {
                    String hintText;
                    if (state == 4) {
                        hintText = getString(R.string.error_print_paper) + "（" + mCountDownTime + "s）";
                    } else if (state == 5) {
                        hintText = getString(R.string.error_printer_hot) + "（" + mCountDownTime + "s）";
                    } else {
                        hintText = getString(R.string.error_printer) + "（" + mCountDownTime + "s）";
                    }
                    mTvHint.setText(hintText);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            if (mCountDownTime == 60) {
                mHandler.removeMessages(0);
                handlePrintSuccess();
            } else {
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UIUtils.screenMonopoly(1);
        init();
    }

    private void init() {
        Intent intent = getIntent();
        mTitleResId = intent.getIntExtra("extra_title", 0);
        mIconResId = intent.getIntExtra("extra_icon", 0);
        mResultStr = intent.getStringExtra("extra_result");
        mPayDetail = (PayDetail) intent.getSerializableExtra("extra_payDetail");

        boolean isScanCodePrint = SalesSlipPrintSettingsOperation.getInstance().getSalesSlipPrintSettings().isScanCodePrint(); // 扫码类交易打印凭条
        boolean isPrint = Params.sL3Params == null || Params.sL3Params.isPrintTicket ||
                mPayDetail.transPlatform == 0 || isScanCodePrint;
        if (isPrint) {
            setContentView(R.layout.transaction_activity_wait_printer);
            initView();
            startPrint();
        } else {
            // 如果外调程序不打印小票的话
            handlePrintSuccess();
        }
    }

    private void initView() {
        TitleView titleView = findViewById(R.id.title_view);
        titleView.setLeftImageVisibility(View.GONE);
        titleView.setCenterText(mTitleResId);

        mIvState = findViewById(R.id.iv_state);
        mTvState = findViewById(R.id.tv_state);
        mTvHint = findViewById(R.id.tv_hint);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    // 开始打印
    private void startPrint() {
        executeTask(
                () -> {
                    try {
                        int state = DataPrinterKernel.INSTANCE().updatePrinterState();
                        if (state == 1) {
                            runOnUI(
                                    () -> {
                                        mIvState.setBackgroundResource(R.drawable.state_print);
                                        mTvState.setText(R.string.index_print);
                                        mTvHint.setText(R.string.index_print_ing);
                                    }
                            );
                            new PrintController().print(mPayDetail, mPrintCallback, 1, false);
                        } else {
                            handlePrintException(state);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        handlePrintException(0);
                    }
                }
        );
    }

    // 恢复打印
    private void resetPrint() {
        executeTask(
                () -> {
                    try {
                        runOnUI(
                                () -> {
                                    mIvState.setBackgroundResource(R.drawable.state_print);
                                    mTvState.setText(R.string.index_print);
                                    mTvHint.setText(R.string.index_print_ing);
                                }
                        );
                        new PrintController().print(mPayDetail, mPrintCallback, 1, false);
                    } catch (Exception e) {
                        e.printStackTrace();
                        handlePrintSuccess();
                    }
                }
        );
    }

    private void handlePrintException(int state) {
        runOnUI(
                () -> {
                    LogUtil.e(Configs.TAG, "打印机状态异常:" + state);
                    mIvState.setBackgroundResource(R.drawable.state_print_failed);
                    mTvState.setText(R.string.index_print_fail);
                    if (state == 4) {
                        mTvState.setText(R.string.error_print_paper);
                    } else if (state == 5) {
                        mTvState.setText(R.string.error_printer_hot);
                    } else {
                        mTvState.setText(R.string.error_printer);
                    }
                    mCountDownTime = 0;
                    if (mHandler != null) {
                        mHandler.sendEmptyMessage(0);
                    }
                }
        );
    }

    private void handlePrintSuccess() {
        runOnUI(
                () -> {
                    mIvState.setBackgroundResource(R.drawable.state_print_success);
                    mTvState.setText(R.string.index_print_success);
                    mTvHint.setText(R.string.index_print_keep_ticket);

                    // 根据终端交易流水号更新的是否已打印标志
                    mPayDetailModel.updateIsPrintedByVoucherNo(mPayDetail.voucherNo, true);
                    ResultActivity.startAction(mActivity, mTitleResId, mIconResId, mResultStr, mPayDetail);
                    finish();
                }
        );
    }

    private ICallback mPrintCallback = new BasePrintCallback() {

        @Override
        public void onPrintResult(int code, String msg) throws RemoteException {
            LogUtil.e(Configs.TAG, "code:" + code + " msg:" + msg);
            if (code == 0) {
                handlePrintSuccess();
            } else {
                handlePrintException(code);
            }
        }

    };

    public static void startAction(Context context, int titleResId, PayDetail payDetail) {
        startAction(context, titleResId, 0, "", payDetail);
    }

    public static void startAction(Context context, int titleResId, int iconResId, String result, PayDetail payDetail) {
        Intent intent = new Intent(context, WaitPrintActivity.class);
        intent.putExtra("extra_title", titleResId);
        intent.putExtra("extra_icon", iconResId);
        intent.putExtra("extra_result", result);
        intent.putExtra("extra_payDetail", payDetail);
        context.startActivity(intent);
    }

}
